﻿using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using Microsoft.ServiceBus.Messaging;
using Nardax.Azure.ServiceBus;
using Nardax.Samples.ServiceBus;
using System;
using System.Threading.Tasks;

namespace Nardax.Samples.ServiceBusTopicSender
{
    class Program
    {
        static void Main(string[] args)
        {
            // could be just one or more than two
            var connectionStrings = new[] { "Endpoint One", "Endpoint Two" };
            var topicDescription = new TopicDescription("RP-TEST");
            var retryPolicy = new RetryPolicy(new ServiceBusTransientErrorDetectionStrategy(), RetryStrategy.DefaultExponential);

            var topicAdapterDescription = new TopicAdapterDescription
            {
                ConnectionStrings = connectionStrings,
                TopicDescription = topicDescription,
                RetryPolicy = retryPolicy
            };

            var topicAdapter = new TopicAdapter(topicAdapterDescription);

            for (int i = 0; i < 1; i++)
            {
                Task.Factory.StartNew(() => SendMessages(topicAdapter));
            }

            Console.ReadLine();
        }

        public static void SendMessages(ITopicAdapter topicAdapter)
        {
            var count = 0;
            while (true)
            {
                //Console.WriteLine("Sending: {0}", count);
                var message = new NardaxBrokeredMessage(count++);

                try
                {
                    topicAdapter.TrySend(message);
                    Console.WriteLine("Sending: {0}", count);
                    //Console.WriteLine("Message sent: {0}", count);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Send failed: {0}", count);
                    Console.WriteLine(ex);
                }
            }
        }
    }
}
